<script setup>
import {listUser} from "@/api/system/user.js";
import {defineModel} from "@vue/runtime-core";
import  {listProduct} from "@/api/base/product";
import  {getPlan,getPlanList} from "@/api/production/plan.js";
import {listDept} from "@/api/system/dept.js";
import {ElMessage} from "element-plus";
import {addOrder, getOrder, updateOrder} from "@/api/production/order.js";

const emit = defineEmits(['getList']);
const open = defineModel('open');
const loading = ref(true);
const title = defineModel('title');
const ins = defineModel('ins')
const id = defineModel('id');
let form = reactive({
  planId: null,
  workOrderName: null,
  staffId: null,
  productDeptId: null,
  productionCount: null,
  productionNo: null,
  planStartTime: null,
  planEndTime: null,
  productionWorkOrderDetailList:[],
  rules: {
    planId: [
      {required: true, message: "计划id不能为空", trigger: "blur"}
    ],
    workOrderName: [
      {required: true, message: "工单名称不能为空", trigger: "blur"}
    ],
    staffId: [
      {required: true, message: "负责人不能为空", trigger: "blur"}
    ],
    productDeptId: [
      {required: true, message: "生产小组不能为空", trigger: "blur"}
    ],
    productionCount: [
      {required: true, message: "产品数量不能为空", trigger: "blur"}
    ],
    productionNo: [
      {required: true, message: "产品批次号不能为空", trigger: "blur"}
    ],
    planStartTime: [
      {required: true, message: "产品生产预期开始时间不能为空", trigger: "blur"}
    ],
    planEndTime: [
      {required: true, message: "产品生产预期结束时间不能为空", trigger: "blur"}
    ],
    productionWorkOrderDetailList:[
      {required: true, message: "产品不能为空", trigger: "blur"}
    ]
  }
})
const goodsList = ref([])
const options =ref([])
const planList = ref([])
const deptList = ref([])
let userList = reactive([])
//获取用户
function getUsers(){
  listUser().then(response => {
    userList = response.rows
  });
}
//获取产品
function getProduct(){
  listProduct().then(resp => {
    resp.rows.filter(p => {
      options.value.push({
        productId:p.id,
        productName:p.productName,
        price:p.price
      })
    })
  })
}
//获取计划
function getPlans(){
  let query = {
    status : 0
  }
  getPlanList(query).then(response => {
    for (let i = 0; i < response.rows.length; i++) {
      planList.value.push({
        id:response.rows[i].id,
        status:response.rows[i].status,
        planName:response.rows[i].planName
      })
    }
  })
}
//获取生产部门
function getDept(){
  let query = {
    parentId:202
  }
  listDept(query).then(response => {
    for (let i = 0; i < response.data.length; i++) {
      deptList.value.push({
        id:response.data[i].deptId,
        deptName:response.data[i].deptName
      })
    }
  })
}
//当修改或者查看详情时获取当前工单
function getOrderDetail(){
  getOrder(id.value).then(response => {
    form.planId = response.data.planId;
    form.workOrderName=response.data.workOrderName
    form.staffId=response.data.staffId
    form.productDeptId=response.data.productDeptId
    form.productionCount=response.data.productionCount
    form.productionNo=response.data.productionNo
    form.planStartTime=response.data.planStartTime
    form.planEndTime=response.data.planEndTime
    for (let i = 0; i < response.data.productionWorkOrderDetailList.length; i++) {
      goodsList.value.push({
        goodName:'',
        number:response.data.productionWorkOrderDetailList[i].productionCount,
        productId:response.data.productionWorkOrderDetailList[i].productionId,
      })
    }
  })
}
// 表单重置
function reset() {
  form.id= null
  form.planId= null
  form.workOrderName= null
  form.staffId= null
  form.productDeptId= null
  form.productionCount= null
  form.productionNo= null
  form.planStartTime= null
  form.planEndTime= null
  form.productionWorkOrderDetailList=[]
  goodsList.value=[]
}
// 取消按钮
function cancel() {
  reset();
  open.value = false;
}
//选择计划进行回填
function selectPlan(){
  getPlan(form.planId).then(response => {
    goodsList.value=[]
    form.productionCount=0
    for (let i = 0; i < response.data.productionPlanDetails.length; i++) {
      goodsList.value.push({
        goodName:'',
        number:response.data.productionPlanDetails[i].productionNumber,
        productId:response.data.productionPlanDetails[i].productionId,
      })
      form.productionCount += response.data.productionPlanDetails[i].productionNumber
    }
  })
}
/** 添加按钮操作 */
function handleAddTGoods() {
  let obj = {};
  obj.goodName = "";
  obj.number = 0;
  goodsList.value.push(obj);
}
function handleDeleteTGoods(index) {
  //删除当前行
  goodsList.value.splice(index, 1);
  numberChange()
}
function numberChange(){
  if (goodsList.value===null || goodsList.value ===undefined || goodsList.value.length === 0){
    form.productionCount = 0
  }else {
    form.productionCount = 0
    for (let i = 0; i < goodsList.value.length; i++) {
      form.productionCount += goodsList.value[i].number
    }
  }
}
// 生成生产工单单名以及产品批次号
function productionNameAndNo(){
  if (form.planStartTime!==''){
    form.workOrderName = form.planStartTime.substring(0,4)+'年'+form.planStartTime.substring(5,7)+'月'+
        form.planStartTime.substring(8,10)+'日'+'生产工单'
    form.productionNo="SC"+new Date().getTime();
  }
}
/** 提交按钮 */
function submitForm(){
  if (goodsList.value === null || goodsList.value === undefined || goodsList.value.length === 0){
    ElMessage.error("请选择产品")
  }else {
    for (let i = 0; i < goodsList.value.length; i++) {
      form.productionWorkOrderDetailList.push({
        productionId:goodsList.value[i].productId,
        productionCount:goodsList.value[i].number,
      })
    }
    console.log('form')
    console.log(form)
    if (title.value==='添加生产工单'){
      addOrder(form).then(response => {
        if (response.code === 200) {
          ElMessage.success("新增成功");
          cancel();
          emit('getList');
        } else {
          ElMessage.error(response.msg);
        }
      })
    }else {
      form.id = id.value
      updateOrder(form).then(response => {
        if (response.code === 200) {
          ElMessage.success("修改成功");
          cancel();
          emit("getList");
        } else {
          ElMessage.error(response.msg);
        }
      })
    }

  }
}
onMounted(() => {
  loading.value=true
  getUsers()
  getProduct()
  getPlans()
  getDept()
  loading.value=false
})
watch(ins,()=>{
  console.log(ins.value)
  if (ins.value){
    getOrderDetail()
  }
})

</script>

<template>
  <el-dialog v-loading="loading" :title="title" width="700px" @close="reset">
    <el-form :disabled="title === '查看生产工单'" ref="orderRef" :model="form" :rules="form.rules" label-width="180px">
      <el-form-item label="计划" prop="planId">
        <el-select :disabled="title === '修改生产工单'" v-model="form.planId" placeholder="请选择计划" @change="selectPlan()">
          <el-option v-for="item in planList" :key="item.id" :label="item.planName" :value="item.id"  :disabled="item.status != 1" />
        </el-select>
      </el-form-item>
      <el-form-item label="工单名称" prop="workOrderName">
        <el-input disabled v-model="form.workOrderName" placeholder="工单名称自动生成"/>
      </el-form-item>
      <el-form-item label="负责人" prop="staffId">
        <el-select v-model="form.staffId" placeholder="请选择计划负责人" >
          <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId" />
        </el-select>
      </el-form-item>
      <el-form-item label="生产小组" prop="productDeptId">
        <el-select v-model="form.productDeptId" placeholder="请选择生产小组" >
          <el-option v-for="item in deptList" :key="item.id" :label="item.deptName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="生产产品" >

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddTGoods">添加</el-button>
          </el-col>
        </el-row>

        <el-table :data="goodsList" >
          <el-table-column label="产品名字" prop="goodName" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.productId"   placeholder="选择产品" style="width: 120px">
                <el-option
                    v-for="item in options"
                    :key="item.productName"
                    :label="item.productName"
                    :value="item.productId"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="number" width="165">
            <template #default="scope">
              <el-input-number min="1" v-model="scope.row.number" placeholder="请输入数量" @change="numberChange" />
            </template>
          </el-table-column>
          <el-table-column label="操作" prop="number" width="150">
            <template #default="scope">
              <el-button type="danger" icon="Delete"  @click="handleDeleteTGoods(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>


      </el-form-item>
      <el-form-item label="产品数量" prop="productionCount">
        <el-input disabled v-model="form.productionCount" placeholder="产品数量自动计算"/>
      </el-form-item>
      <el-form-item label="产品批次号" prop="productionNo">
        <el-input disabled v-model="form.productionNo" placeholder="产品批次号自动生成"/>
      </el-form-item>
      <el-form-item label="产品生产预期开始时间" prop="planStartTime" >
        <el-date-picker clearable
                        v-model="form.planStartTime"
                        @change="productionNameAndNo"
                        type="datetime"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        placeholder="请选择生产预期开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="产品生产预期结束时间" prop="planEndTime">
        <el-date-picker clearable
                        v-model="form.planEndTime"
                        type="datetime"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        placeholder="请选择生产预期结束时间">
        </el-date-picker>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="title === '查看生产工单'">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>